<script type="text/javascript">
    function jqxFixColumns(columns){
        try{
        columns['Sold'].validation= function (cell, value) {
            if (value < 0 || value > 1000) {
                return { result: false, message: "Sold should be in the 0-1000 interval" };
            }
            return true;
        };
        columns['Sold'].createeditor=function (row, cellvalue, editor) {
            editor.jqxNumberInput({ decimalDigits: 0 });
        };
        
        columns['Amount'].validation= function (cell, value) {
            if (value < 0 || value > 1000) {
                return { result: false, message: "Amount should be in the 0-1000 interval" };
            }
            return true;
        };
        columns['Amount'].createeditor=function (row, cellvalue, editor) {
            editor.jqxNumberInput({ decimalDigits: 0 });
        };
        
        columns['UnitPrice'].validation= function (cell, value) {
            if (value < 1000) {
                return { result: false, message: "Amount should be less than 1000" };
            }
            return true;
        };
        columns['UnitPrice'].createeditor=function (row, cellvalue, editor) {
            editor.jqxNumberInput({ decimalDigits: 0,spinButtonsStep:1000 });
        };
        
        columns['UnitsOnOrder'].validation= function (cell, value) {
            if (value < 1000) {
                return { result: false, message: "UnitsOnOrder should be less than 1000" };
            }
            return true;
        };
        columns['UnitsOnOrder'].createeditor=function (row, cellvalue, editor) {
            editor.jqxNumberInput({ decimalDigits: 0,spinButtonsStep:1000 });
        };
        
        columns['ProductName'].validation= function (cell, value) {
            if (value =="") {
                return { result: false, message: "ProductName should be non-empty." };
            }
            return true;
        };
        }catch(e){tipMessage(e.message);}
        return columns;
    }
    function handleEvent_jqxGrid(jqxgrid){
        jqxgrid.bind('cellendedit', function (event) {
            try{
                var args = event.args;
                var Column = args.datafield ,Row = args.rowindex,Value = args.value;
                var Data=jqxgrid.jqxGrid('getrowdata', Row);
                var ID=Data.ID;
                if(ID==undefined || ID==""){
                    return;
                }
                switch(Column){
                    case "Status":
                        updateCol("Status",ID,Value);
                        break;
                    case "QuantityPerUnit":
                        if(Data.QuantityPerUnit!=Value){
                            updateCol("QuantityPerUnit",ID,Value);
                        }
                        break;
                    case "ProductName":
                        if(Data.ProductName!=Value){
                            updateCol("ProductName",ID,Value);
                        }
                        break;
                    case "UnitsOnOrder":
                        if(Data.UnitsOnOrder!=Value){
                            updateCol("UnitsOnOrder",ID,Value);
                        }
                        break;
                    case "UnitPrice":
                        if(Data.UnitPrice!=Value){
                            updateCol("UnitPrice",ID,Value);
                        }
                        break;
                    case "Amount": 
                        if(Data.Amount!=Value){
                            updateCol("Amount",ID,Value);
                        }
                        break;
                    case "Sold":
                        if(Data.Sold!=Value){
                            updateCol("Sold",ID,Value);
                        }
                        break;
                    default:
                    tipMessage("Unkown this cell. Maybe 'editable' of this colums is 'off'"); 
                }
            }catch(e){
                tipMessage(e.message);
                console.log("Error:"+e.message);
            }
        });
    }
    function SaveItem(){
        try{
            var res=$("#cbxRegions").jqxDropDownList('getCheckedItems');
            if( res==undefined || res.length==0){
                tipMessage("Khu vực phải được chọn ít nhất 1.");
                return;
            }
            var cas=$("#cbxCategorys").jqxDropDownList('getCheckedItems');
            if( cas==undefined || cas.length==0){
                tipMessage("Danh mục phải được chọn ít nhất 1.");
                return;
            }
            
            if(isrunning)return;
            console.log("Save ↵ Call");
            var Content,Regions=new Array(),Categorys=new Array(),Album=new Array();
            Content =  tinyMCE.get('txtContent').getContent();//$('#txtContent').getCode();//areaContent.instanceById('txtContent').getContent();//
            for(var i=0;i<res.length;i++){
                Regions[i]=res[i].value
            }
            for(var i=0;i<cas.length;i++){
                Categorys[i]=cas[i].value
            }
            var tmp =$("#AlbumItems img").map(function() {
                return $(this).attr("src");
            });
            for(var i=0;i<tmp.length;i++){
                Album[i]=tmp[i];
            }
            var url="{{base_url()}}APanel/{{$controller}}/Save";
            var data={
                ID              :   $('#txtID').val(),
                Name            :   $('#txtName').val(),
                Title           :   $('#txtTitle').val(),
                Image           :   $('#txtImage').val(),
                Categorys       :   Categorys,
                Regions         :   Regions,
                Album           :   Album,
                Supplier        :   $('#txtSupplier').val(),
                QuantityPerUnit :   $('#txtQuantityPerUnit').val(),
                Amount          :   $('#txtAmount').val(),
                Sold            :   $('#txtSold').val(),
                UnitPrice       :   $('#txtUnitPrice').val(),
                UnitsOnOrder    :   $('#txtUnitsOnOrder').val(),
                StartDate       :   $('#txtStartDate').val(),
                EndDate         :   $('#txtEndDate').val(),
                Tag             :   $('#txtTag').val(),
                Feature         :   $('#txtFeatures').val(),
                Condition       :   $('#txtConditions').val(),
                Content         :   Content
            }
            if (!confirm("Lưu các thông tin lại!")) return;
            console.log(data);
            isrunning=true;
            jqxAjax(url,data,function(result){
                isrunning=false;
                if(result.code>=0){
                    myjqxGrid.CancelEdit();
                    myjqxGrid.Refresh();
                }else{
                    ShowErrorDialogMessage(result.msg);
                }
            });
        }catch(e){
            console.log("JSON Error:"+e.message+"\n↵ Error");
            tipMessage(e.message);
            //ShowErrorDialogMessage("Sorry. Your request could not be completed.<br/> Please check your input data.");
        }
    }
    function DelAlbumItem(obj){
        $(obj).parents("div.AlbumItem").remove();
    }
    function AddAlbumItem(){
        var AlbumItems =$("#AlbumItems");
        var srcImg=$("#txtAddImage").val();
        if(!_FcheckFilled(srcImg)){return}
        var AlbumItem=
        '<div class="AlbumItem grid_5 mb4 mt4 ml4 mr4 bdccc gadiend-white">\
            <div class="pt1 pb1 pl1 pr1">\
                <div class="pl8 pt4 pb4 pr8 ovfh mt0 mb0 mr0 ml0 bdbccc">\
                    Album item\
                </div>\
                <div class="pa r8 t4">\
                    <span class="hover50" style="cursor: pointer" onclick="DelAlbumItem(this)">✖</span>\
                </div>\
                <div class="pl4 pr4 pt4 pb4 mt0 mb0 ml0 mr0 ovfa pr" style="height: 220px">\
                    <img src="'+srcImg+'"/>\
                </div>\
            </div>\
        </div>';
        AlbumItems.append(AlbumItem);
        $("#txtAddImage").val("");$("#txtAddImage").focus();
    }
    function CreateDatetimeElement(Start,End){
        $(Start).datetimepicker({
            ampm: false,dateFormat: 'yy-mm-dd',
            onClose: function(dateText, inst) {
                var endDateTextBox = $(End);
                if (endDateTextBox.val() != '') {
                    var testStartDate = new Date(dateText);
                    var testEndDate = new Date(endDateTextBox.val());
                    if (testStartDate > testEndDate)
                        endDateTextBox.val(dateText);
                }
                else {
                    endDateTextBox.val(dateText);
                }
            },
            onSelect: function (selectedDateTime){
                var start = $(this).datetimepicker('getDate');
                $(End).datetimepicker('option', 'minDate', new Date(start.getTime()));
            }
        });
        $(End).datetimepicker({
            ampm: false,dateFormat: 'yy-mm-dd',
            onClose: function(dateText, inst) {
                var startDateTextBox = $(Start);
                if (startDateTextBox.val() != '') {
                    var testStartDate = new Date(startDateTextBox.val());
                    var testEndDate = new Date(dateText);
                    if (testStartDate > testEndDate)
                        startDateTextBox.val(dateText);
                }
                else {
                    startDateTextBox.val(dateText);
                }
            },
            onSelect: function (selectedDateTime){
                var end = $(this).datetimepicker('getDate');
                $(Start).datetimepicker('option', 'maxDate', new Date(end.getTime()) );
            }
        });
    }
</script>